package com.version1_2.service.implement;


import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.util.format.MapToJson;
import com.util.property.Properties;
import com.version1_1.dao.UserDao;
import com.version1_1.service.UserService;
import com.version1_2.dao.UserDao1_2;
import com.version1_2.service.UserService1_2;
import com.version1_3.service.CoinService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService12Impl implements UserService1_2 {

    /*创建log4j对象*/
    private static final Logger LOGGER = Logger.getLogger(UserService12Impl.class);

    @Autowired
    private UserDao1_2 userDao12;

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserService userService;

    @Autowired
    private CoinService coinService;

    /**
     * @Description: 更改密码
     */
    @Override
    public String updatePasswd(JSONObject jsonObject) {
        boolean updatePasswdResult = userDao.updatePasswd(
                jsonObject.getIntValue("userId"),
                jsonObject.getString("newPasswd"));

        if (updatePasswdResult) {
            return "{\"updatePasswdResult\":true}";
        } else {
            return "{\"updatePasswdResult\":false}";
        }
    }

    /**
     * @Description: 更新用户个人信息
     */
    @Override
    public String updateUserInfo(JSONObject jsonObject) {

        int userId = jsonObject.getIntValue("userId");
        String userName = jsonObject.getString("userName");
        String userPhoto = jsonObject.getString("userPhoto");
        String userSex = jsonObject.getString("userSex");
        String school = "";
        int schoolYear = -1;

        try {
            school = jsonObject.getString("school");
        } catch (JSONException exception) {
            LOGGER.error("更新用户个人信息,Json字符串中没有key: school");
        }
        try {
            schoolYear = jsonObject.getIntValue("schoolYear");
        } catch (JSONException exception) {
            LOGGER.error("更新用户个人信息,Json字符串中没有key: schoolYear");
        }

        return "{\"updateResult\":" + userDao.updateUserInfo(userId, userName, userPhoto, userSex, school, schoolYear) + "," + userDao.getUserInfo(userId).toString() + "}";
    }

    /**
     * @description: 更新用户关注列表
     */
    @Override
    public String updateFocusList(JSONObject jsonObject) {
        boolean result = userDao12.updateFocusList(jsonObject);
        return "{\"focusUpdateResult\":" + result + "}";
    }

    /**
     * @description: 用户反馈
     */
    @Override
    public String feedback(JSONObject feedbackJson) {
        int userId = feedbackJson.getIntValue("userId");
        String feedbackType = feedbackJson.getString("feedbackType");
        String feedbackDate = feedbackJson.getString("feedbackDate");
        String feedbackContent = feedbackJson.getString("feedbackContent");

        /*截图最多4张，image采用String字符串数据格式*/
        String screenShot1 = (feedbackJson.getString("screenShot1") == null) ? null : feedbackJson.getString("screenShot1");
        String screenShot2 = (feedbackJson.getString("screenShot2") == null) ? null : feedbackJson.getString("screenShot2");
        String screenShot3 = (feedbackJson.getString("screenShot3") == null) ? null : feedbackJson.getString("screenShot3");
        String screenShot4 = (feedbackJson.getString("screenShot4") == null) ? null : feedbackJson.getString("screenShot4");

        return "{\"feedbackResult\":" + userDao.feedback(userId, feedbackType,
                feedbackDate, feedbackContent, screenShot1, screenShot2, screenShot3, screenShot4) + "}";

    }

    /**
     * @description: 记录用户收藏
     */
    @Override
    public String doCollect(JSONObject jsonObject) {
        boolean doCollectResult = false;
        try {
            int userId = jsonObject.getIntValue("userId");
            int pageId = jsonObject.getIntValue("pageId");
            int actionType = jsonObject.getIntValue("actionType");

            if (actionType == 1) {
                coinService.moduleRecord(userId, "information", "collectArticle", 5, 1, 10); // 用户收藏文章,增加积分
            }

            doCollectResult = userDao.doCollect(userId, pageId, actionType);
        } catch (EmptyResultDataAccessException exception) {
            LOGGER.error("记录用户收藏,解析collectString错误...", exception);
        }

        return "{\"collectResult\":" + doCollectResult + "}";
    }

    /**
     * @Description: 登录用户得到收藏列表
     */
    @Override
    public String getCollectList(int userId, int pageNumber) {
        List<Map<String, Object>> collectList = userDao12.getCollectList(userId, pageNumber);
        Map<String, Object> collectMap = new HashMap<>(); // 数据Map

        // 如果收藏列表为空或者获取错误
        if (collectList == null || collectList.isEmpty()) {
            LOGGER.info("用户收藏列表为空或为null...");
            return "{\"collectList\":[]}";
        }

        String secondTypeID = ""; //二级分类名称
        Map<String, Object> secondNameMap = new HashMap<>(); //二级分类名称和数量Map

        /**
         * 对图片URL进行处理
         */
        for (Map<String, Object> tempMap : collectList) {
            tempMap.replace("imageSrc", tempMap.get("imageSrc") + Properties.ImageLowQuality);
        }

        /**
         * 如果是第一页
         */
        if (pageNumber == 1) {

            /*获取总的收藏数据*/
            List collectListAll = userDao.getCollectList(userId);

            // 如果收藏列表为空或者获取错误
            if (collectListAll == null || collectListAll.isEmpty())
                return "{\"collectList\":[]}";

            for (int i = 0; i < collectListAll.size(); i++) {
                Map replyMap = (Map) collectListAll.get(i);
                String thirdTypeName = (String) replyMap.get("thirdTypeName");

            /*----------------分析二级分类名称和数量----------------*/
                secondTypeID = userDao.getSecondIdByThirdName(thirdTypeName);

                if (secondTypeID != null) {
                    if (!secondNameMap.containsKey(secondTypeID)) {
                        secondNameMap.put(secondTypeID, 1);
                    } else {
                        secondNameMap.put(secondTypeID, (int) secondNameMap.get(secondTypeID) + 1);
                    }
                }
            }

            net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(secondNameMap);
            collectMap.put("count", collectListAll.size());
            collectMap.put("secondTypeList", jsonArray);
        }

        collectMap.put("collectList", collectList);

        return net.sf.json.JSONObject.fromObject(collectMap).toString();
    }

    /**
     * @Description: 根据二级分类ID获取用户收藏中特定的二级分类的文章
     */
    @Override
    public String getSecondTypeCollectList(int userId, int secondType, int pageNumber) {
        List<Map> secondCollectList = userDao12.getSecondCollectList(userId, secondType, pageNumber);

        // 如果二级分类收藏列表为空或者获取错误
        if (secondCollectList == null || secondCollectList.isEmpty()) {
            return "{\"secondCollectList\":[]}";
        } else {
            for (Map collectMap : secondCollectList) {
                collectMap.replace("imageSrc", (String) collectMap.get("imageSrc") + Properties.ImageLowQuality);
            }
        }

        return new MapToJson("secondCollectList", secondCollectList).toJsonString();
    }




    /*------------------------------------------ 复用version1.1中userService层中部分功能 ------------------------------------------*/

    /**
     * 用户登陆
     */
    @Override
    public String userLogin(int userId, String mail, String telnumber,
                            String password,String baiduId) {
        return userService.userLogin(userId, mail, telnumber, password,baiduId);
    }

    /**
     * 登陆用户删除收藏
     */
    @Override
    public String delCollect(int userId, String deleteList) {
        return userService.delCollect(userId, deleteList);
    }

    /**
     * 检测用户输入的手机号或者邮箱号是否已经被注册
     */
    @Override
    public boolean checkRegister(String registerInfo) {
        return userService.checkRegister(registerInfo);
    }

    /**
     * 忘记密码
     */
    @Override
    public boolean forgetPass(String telnumber, String newPassword) {
        return userService.forgetPass(telnumber, newPassword);
    }

}
